/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import beans.B_Persona;
import beans.B_PersonaEmail;
import db.DB_PersonaEmail;
import java.util.ArrayList;

/**
 *
 * @author JoseHernan
 */
public class C_PersonaEmail extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession(true);
        //Preguntamos si estamos logueados
        if (session.getAttribute("userName") != null) {
            String action = request.getParameter("action2");
            String userName = session.getAttribute("userName").toString();
            String mensaje = "";
            int flagAccion = 0;
            String id = request.getParameter("id2");
            //Parameters
            int idPersona = Integer.parseInt(request.getParameter("idPersona"));
            String email;

            B_PersonaEmail obj;
            B_Persona objPersona;
            //New
            if (action.equals("n")) {
                //Set Parameters
                email = request.getParameter("email");
                obj = new B_PersonaEmail();
                obj.setId(Integer.parseInt(id));
                obj.setEmail(email);
                objPersona = new B_Persona();
                objPersona.setId(idPersona);
                obj.setObjPersona(objPersona);
                obj.setUser(userName);
                mensaje = DB_PersonaEmail.crud(obj, action);
                flagAccion = 1;
            } //Update
            else if (action.equals("u")) {
                //Set Parameters
                email = request.getParameter("email");
                obj = new B_PersonaEmail();
                obj.setId(Integer.parseInt(id));
                obj.setEmail(email);
                objPersona = new B_Persona();
                objPersona.setId(idPersona);
                obj.setObjPersona(objPersona);
                obj.setUser(userName);
                mensaje = DB_PersonaEmail.crud(obj, action);
                flagAccion = 1;
            } //Delete
            else if (action.equals("d")) {
                obj = new B_PersonaEmail();
                obj.setId(Integer.parseInt(id));
                mensaje = DB_PersonaEmail.crud(obj, action);
                flagAccion = 1;
            } else if (action.equals("ds")) {
                String[] itemsDelete = id.split(",");
                //Verificamos que tenga mas de 1 item
                if (itemsDelete.length > 0) {
                    for (int i = 0; i < itemsDelete.length; i++) {
                        obj = new B_PersonaEmail();
                        obj.setId(Integer.parseInt(itemsDelete[i]));
                        mensaje += DB_PersonaEmail.crud(obj, "d");
                        if ((i + 1) < itemsDelete.length) {
                            mensaje += "***";
                        }
                    }
                }
                flagAccion = 1;
            }
            if (flagAccion == 0) {
                mensaje = "La página solicitada no existe.";
                response.sendRedirect("mensaje.jsp?mensaje=" + mensaje + "&pagina=home.jsp");
            } else {
                if (mensaje.equals("OK")) {
                    mensaje += getObjHtml(idPersona);
                }
                out.write(mensaje);
            }
        } else {
            //WITHOUT SESSION
            String mensaje = "Su sesion a expirado, ingrese nuevamente.";
            response.sendRedirect("mensaje.jsp?mensaje=" + mensaje + "&pagina=index.jsp");
        }
    }

    public String getObjHtml(int idPersona) {
        StringBuilder html = new StringBuilder();
        ArrayList<B_PersonaEmail> listPersonaEmail = DB_PersonaEmail.getListFilerByIdPersona(idPersona);
        if (listPersonaEmail.isEmpty()) {
            html.append("<div class=\"Metronic-alerts alert alert-danger fade in\">No se encontraron Registros</div>");
        } else {
            html.append("<table class=\"table table-condensed table-hover table-bordered\">");
            html.append("   <thead>");
            html.append("       <tr>");
            html.append("           <th>Nº</th>");
            html.append("           <th>Email</th>");
            html.append("           <th colspan=\"2\">Acciones</th>");
            html.append("       </tr>");
            html.append("   </thead>");
            html.append("   <tbody>");
            B_PersonaEmail objPersonaEmail;
            for (int i = 0; i < listPersonaEmail.size(); i++) {
                objPersonaEmail = listPersonaEmail.get(i);
                html.append("   <tr>");
                html.append("<td>").append(i + 1).append("</td>");
                html.append("<td>").append(objPersonaEmail.getEmail()).append("</td>");
                html.append("<td>");
                html.append("<a href=\"#basic\" data-toggle=\"modal\" onclick=\"changeDataModalCustom2('View/PersonaEmail/V_PersonaEmail_Update.jsp?action=u&id=").append(objPersonaEmail.getId()).append("&idPersona=").append(idPersona).append("', '40%');\"><i class=\"fa fa-pencil-square\"></i></a>");
                html.append("</td>");
                html.append("<td>");
                html.append("<a href=\"#basic\" data-toggle=\"modal\" onClick=\"changeDataModalCustom2('deleteRowUpdateDOM.jsp?servlet=C_PersonaEmail&action=d&id=").append(objPersonaEmail.getId()).append("&DOMObjet=table_content&idParent=").append(idPersona).append("&idParentName=idPersona', '40%');\"><i class=\"fa fa-trash-o\"></i></a>");
                html.append("</td>");
                html.append("   </tr>");
            }
            html.append("   </tbody>");
            html.append("</table>");
        }
        return html.toString();
    }
}
